<template>
	<SearchBar ref="searchRef" :placeholder="$t('goods_information_consumer.search_placeholder')" v-model="formData" @search-event="val => handleSearchEvent(val)">
		<template #custom_filter>
			<customSearchComponent :searchBarRef="SearchBar"></customSearchComponent>
		</template>
		<template #footer>
			<div v-if="!!props.treeSelected && props.treeSelected !== '0'" v-auth="{ authArr: props.auth, key: 'add' }">
				<el-dropdown v-if="props.treeSelected == '3' || props.treeSelected == '9'" @command="value => emit('add', value)">
					<el-button type="primary">
						{{ $t("goods_archive.add_goods") }}
					</el-button>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item :command="1">套件</el-dropdown-item>
							<el-dropdown-item :command="0">非套件</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
				<el-button v-else type="primary" @click="emit('add')">
					{{ $t("goods_archive.add_goods") }}
				</el-button>
			</div>
		</template>
		<template #searchForm="searchProp">
			<div class="modal-content">
				<div class="modal-title">
					<!-- {{ $t("merak.search_list_ad") }} -->
				</div>
				<div class="modal—body">
					<el-scrollbar class="search_from_scrollbar">
						<div class="scrollbar-content">
							<SelectedParams v-model="formData" />
							<el-form ref="formRef" label-position="top" :model="formValue" :rules="formRules">
								<MerakColapse :is-active="getShow" :min-height="getHeight">
									<template #header>{{ $t("goods_information_consumer.general") }}</template>
									<el-row :gutter="40">
										<template v-for="(item, index) of formMenu?.basic">
											<template v-if="item.type == 'select' || item.type == 'multiple'">
												<template v-if="item.field == 'supplier_id'">
													<el-col :span="span">
														<el-form-item :label="item.title">
															<el-select @change="query=> getColorList(item.field,query)"
																filterable class="qf_select" remote
																:remote-method="query => remoteMethod(query, index)"
																popper-class="own_popper"
																:placeholder="$t('merak.placeholder_select')"
																v-model="formValue[item.field]">
																<el-option :label="oItem?.label" :value="oItem?.value"
																	v-for="oItem in item.values" :key="oItem?.value" />
															</el-select>
														</el-form-item>
													</el-col>
												</template>
												<template v-else-if="item.field == 'goods_certify_id'">
													<el-col :span="span" v-if="eacNumberValue">
														<el-form-item :label="item.title">
															<el-select multiple collapse-tags filterable
																class="qf_select" popper-class="own_popper"
																:placeholder="$t('merak.placeholder_select')" remote
																:remote-method="query => remoteMethod(query, index)"
																v-model="formValue[item.field]"
																@change="query=> selectOption(item.field,query)">
																<el-option :label="oItem?.label" :value="oItem?.value"
																	v-for="oItem in item.values" :key="oItem?.value" />
															</el-select>
														</el-form-item>
													</el-col>
												</template>
												<template v-else-if="item.field == 'supplier_color'">
													<el-col :span="span" v-if="goodsColorList.length > 0">
														<el-form-item :label="item.title">
															<el-select multiple collapse-tags filterable
																class="qf_select" popper-class="own_popper"
																:placeholder="$t('merak.placeholder_select')"
																v-model="formValue[item.field]">
																<el-option :label="oItem?.label" :value="oItem?.value"
																	v-for="oItem in goodsColorList"
																	:key="oItem?.value" />
															</el-select>
														</el-form-item>
													</el-col>
												</template>
												<template v-else>
													<template v-if="Object.keys(optionGroup).indexOf(item.field) != -1">
														<el-col :span="span">
															<el-form-item :label="item.title">
																<el-select multiple collapse-tags filterable
																	class="qf_select" popper-class="own_popper"
																	:placeholder="$t('merak.placeholder_select')" 
																	remote
																	:remote-method="query => remoteMethod(query, index)"
																	v-model="formValue[item.field]"
																	@change="query=> selectOption(item.field,query)">
																	<el-option :label="oItem?.label"
																		:value="oItem?.value"
																		v-for="oItem in item.values"
																		:key="oItem?.value" />
																</el-select>
															</el-form-item>
														</el-col>
													</template>
													<template v-else>
														<el-col :span="span">
															<el-form-item :label="item.title">
																<el-select multiple collapse-tags filterable
																	class="qf_select" popper-class="own_popper"
																	:placeholder="$t('merak.placeholder_select')"
																	v-model="formValue[item.field]">
																	<el-option :label="oItem?.label"
																		:value="oItem?.value"
																		v-for="oItem in item.values"
																		:key="oItem?.value" />
																</el-select>
															</el-form-item>
														</el-col>
													</template>
												</template>
											</template>
											<el-col :span="span" v-else>
												<el-form-item v-if="item.type == 'radio'" :label="item.title"
													@change="rId => editFormValue(rId, item.field)">
													<el-radio-group v-model="formValue[item.field]">
														<el-radio v-for="oItem of item.values"
															:value="oItem.value">{{ oItem.label }}</el-radio>
													</el-radio-group>
												</el-form-item>
												<el-form-item v-else-if="item.type == 'input'" :label="item.title">
													<el-input class="qf_input" type="text"
														v-model="formValue[item.field]" />
												</el-form-item>
												<el-form-item v-else-if="item.type == 'dateTimeRange'"
													:label="item.title">
													<el-date-picker class="qf_date" type="datetimerange"
														v-model="formValue[item.field]"
														:popper-options="{placement: 'bottom-end'}"
														:range-separator="$t('merak.rangto')"
														:format="renderFormat('YYYY-MM-DD HH:mm')"
														:value-format="renderFormat('YYYY-MM-DD HH:mm')" />
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</MerakColapse>
								<MerakColapse :is-active="false" v-if="formMenu?.prop && formMenu?.prop.length > 0">
									<template #header>{{ $t("goods_information_consumer.prop") }}</template>
									<el-row :gutter="40">
										<template v-for="item of formMenu?.prop">
											<el-col :span="span">
												<el-form-item v-if="item.type == 'radio'" :label="item.title">
													<el-radio-group v-model="formValue[item.field]">
														<el-radio v-for="oItem of item.values"
															:value="oItem.value">{{ oItem.label }}</el-radio>
													</el-radio-group>
												</el-form-item>
												<el-form-item
													v-else-if="item.type == 'select' || item.type == 'multiple'"
													:label="item.title">
													<el-select multiple collapse-tags filterable class="qf_select"
														popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="formValue[item.field]">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in item.values" :key="oItem?.value" />
													</el-select>
												</el-form-item>
												<el-form-item v-else-if="item.type == 'input'" :label="item.title">
													<el-input :maxlength="100" class="qf_input" type="text"
														v-model="formValue[item.field]" />
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</MerakColapse>
								<MerakColapse :is-active="false"
									v-if="formMenu?.cc_prop && formMenu?.cc_prop.length > 0">
									<template #header>{{ $t("goods_information_consumer.cc_prop") }}</template>
									<el-row :gutter="40">
										<template v-for="item of formMenu?.cc_prop">
											<el-col :span="span">
												<el-form-item v-if="item.type == 'radio'" :label="item.title">
													<el-radio-group v-model="formValue[item.field]">
														<el-radio v-for="oItem of item.values"
															:value="oItem.value">{{ oItem.label }}</el-radio>
													</el-radio-group>
												</el-form-item>
												<el-form-item
													v-else-if="item.type == 'select' || item.type == 'multiple'"
													:label="item.title">
													<el-select multiple collapse-tags filterable class="qf_select"
														popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="formValue[item.field]">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in item.values" :key="oItem?.value" />
													</el-select>
												</el-form-item>
												<el-form-item v-else-if="item.type == 'input'" :label="item.title">
													<el-input :maxlength="100" class="qf_input" type="text"
														v-model="formValue[item.field]" />
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</MerakColapse>
							</el-form>
						</div>
					</el-scrollbar>
				</div>
				<div class="modal-footer">
					<el-button type="default" @click="handleReset">{{ $t("merak.reset") }}</el-button>
					<el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
					<el-button plain type="primary" v-if="searchProp.closePlan" @click="searchRef?.showPlanModal">{{
            $t("merak.save_search_scheme")
          }}</el-button>
				</div>
			</div>
		</template>
	</SearchBar>
</template>

<script setup lang="ts" name="SearchForm">
	import { getCurrentInstance, ref, reactive, computed, watch, watchEffect, onMounted } from "vue";

	import { FormRules, ElDropdown, ElDropdownMenu, ElDropdownItem, ElButton, ElRow, ElCol, ElForm } from "element-plus";
	import useDateFormat from "@/hooks/useDateFormat";

	import SearchBar from "@/components/SearchBar/index.vue";
	import SelectedParams from "@/components/SearchBar/components/selectedParams.vue";
	import MerakColapse from "@/components/merakColapse/index.vue";

	import { useGlobalStore } from "@/stores/modules/global";

	import { ResultEnum } from "@/enums/httpEnum";

	import { UserAuthType } from "@/api/modules/user";
	import { getDictOptions } from "@/api/modules/sysManage/personnel";
	import { getSearcList, getColor, getGoodsDocumentList } from "@/api/modules/goodsArchive/list/information";
	import I18n from "@/languages/index";
	import searchBar from "@/components/SearchBar/index.js";
	// 注入顶层权限

	const $t = I18n.global.t;
	// import { userItems, newsletterItems, educationItems, jobItems, contractItems } from "../formItems";
	const { renderFormat } = useDateFormat();
	const currentInstance = getCurrentInstance();
	const modelValue = defineModel({ default: {} });
	const t = (message : string = "") => currentInstance?.proxy?.$t(message);
	const props = defineProps<{
		auth ?: UserAuthType;
		type ?: string;
		treeId ?: string;
		setId ?: string;
		tableId ?: string;
		treeSelected ?: string;
		setValue ?: string;
	}>();

	const emit = defineEmits<{
		add : [suite?: 0 | 1];
		fastSearch : [val: any];
		formSearch : [params: Record<string, any>];
		customSearch : [params: Record<string, any>];
	}>();

	const globalStore = useGlobalStore();

	const searchRef = ref<InstanceType<typeof SearchBar>>();

	const formRef = ref<InstanceType<typeof ElForm>>();

	const formMenu = reactive({});
	const optionGroup = reactive({});
	const selectOptionData = ref({});
	const goodsColorList = ref([]);
	const eacNumberValue = ref(false);
	const formValue = ref<Record<string, any>>({});

	const formRules = reactive<FormRules>({});

	const editFormValue = (tag, title : string) => {
		if (title == "eac_number") {
			if (tag.target._value == 1) {
				eacNumberValue.value = true;
			} else {
				eacNumberValue.value = false;
			}
		}
	};
	//过滤
	const remoteMethod = (query : string, index) => {
		if (query) {
			//console.log(selectOptionData[formMenu?.basic[index].field])
			let list = optionGroup[formMenu?.basic[index].field];
			formMenu.basic[index].values = list.filter(item => {
				return item.label.toLowerCase().includes(query.toLowerCase());
			});
		} else {
			formMenu.basic[index].values = [];
		}
	};
	
	const formData = computed({
		get: () => {
			let itemArr = [];
			if (formMenu.basic) {
				itemArr.push(...formMenu.basic);
			}

			if (formMenu.cc_prop) {
				itemArr.push(...formMenu.cc_prop);
			}
			if (formMenu.prop) {
				itemArr.push(...formMenu.prop);
			}
			let data = {};
			for (let item of itemArr) {
				if (item.field == "created_at") {
					if (formValue.value[item.field] != "") {
						data[item.field] = {
							label: item.title,
							value: formValue.value[item.field],
							type: item.type == "multiple" ? "select" : item.type,
							options: [...(item.values ?? [])]
						};
					} else {
						data[item.field] = {
							label: item.title,
							value: formValue.value[item.field],
							type: item.type == "multiple" ? "select" : item.type,
							options: [...(item.values ?? [])]
						};
					}
				} else {
					if(Object.keys(selectOptionData.value).indexOf(item.field) != -1){
						data[item.field] = {
							label: item.title,
							value: formValue.value[item.field],
							type: item.type == "multiple" ? "select" : item.type,
							options: [...(selectOptionData.value[item.field] ?? [])]
						};
					} else {
						data[item.field] = {
							label: item.title,
							value: formValue.value[item.field],
							type: item.type == "multiple" ? "select" : item.type,
							options: [...(item.values ?? [])]
						};
					}
					
				}
			}
			return data;
		},
		set: value => {
			for (let [key, item] of Object.entries(value)) {
				formValue.value[key] = item.value;
			}
		}
	});

	const span = computed(() => (globalStore.language === "ru" ? 8 : 6));

	const selectOption = (key, row) => {
		let arr = [];
		row.map(item=>{
			let rIdx = optionGroup[key].findIndex(t=>t.value == item);
			if(rIdx != -1){
				arr.push(optionGroup[key][rIdx])
			}
		})
		selectOptionData.value[key] = arr;

	}
	//请求商家颜色
	const getColorList = (key, row) => {
		let rIdx = optionGroup[key].findIndex(item=>item.value == row);
		let arr = [];
		if(rIdx != -1){
			arr.push(optionGroup[key][rIdx])
		}
		selectOptionData.value[key] = arr;
		let dataMsg = {
			supplier_id: row
		};
		getColor(dataMsg).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				goodsColorList.value = data;
			}
		});
	};

	//请求单证列表
	const getDocumentList = () => {
		let dataMsg = {
			type_id: props.treeSelected
		};
		getGoodsDocumentList(dataMsg).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				optionGroup["goods_certify_id"] = data;
			}
		});
	};

	const getShow = computed(() => {
		if (Object.keys(formMenu).length == 1) {
			return true;
		} else {
			return false;
		}
	});
	//计算通用搜索高度
	const getHeight = computed(() => {
		if (Object.keys(formMenu).length == 1) {
			return 336;
		} else if (Object.keys(formMenu).length == 2) {
			return 252;
		} else {
			return 168;
		}
	});

	const handleFormItemChange = (params : MerakXFormItemChangeParams) => {
		switch (params.type) {
			case "input":
				if (!!params.data) {
					formValue.value[params.field] = params.data.trim();
				}
				break;
			default:
				break;
		}
	};

	const handleSearchEvent = (val : {
		action ?: "enter" | "plan" | "form";
		params ?: Record<string, any>;
		plan ?: string | number;
		search ?: string;
	}) => {
		console.log(val)
		if (val.action === "plan" && !!val.params) {
			for (let key of Object.keys(formValue.value)) {
				formValue.value[key] = "";
			}
			for (let key of Object.keys(val.params)) {
				if (!key.includes("_options")) {
					formValue.value[key] = val.params[key];
				}
			}
		}
		emit("fastSearch", val);
	};

	const handleSearch = () => {
		formRef.value?.validate(valid => {
			if (valid) {
				const params = searchRef.value?.formParams("value");
				if (!!params) {
					emit("formSearch", params);
				}
				searchRef.value?.clear();
				searchRef.value?.modalHide();
			}
		});
	};

	const handleReset = () => {
		Object.keys(formValue.value).map(item => {
			formValue.value[item] = undefined;
		});
		formRef.value?.resetFields();
		searchRef.value?.clear();
		const timer = requestAnimationFrame(() => {
			const params = searchRef.value?.formParams("value");
			if (!!params) {
				emit("formSearch", params);
			}
			cancelAnimationFrame(timer);
		});
	};
	const formItems = async (treeValue, setValue) => {
		let dataMsg = {
			type_id: treeValue,
			set: setValue,
			type: props.type
		};
		getSearcList(dataMsg).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				let itemArr = [];
				if (data.basic) {
					itemArr.push(...data.basic);
					let newBasic = Object.assign(data.basic);
					//通用option超过500,单独加载
					newBasic.map((item, index) => {
						if (item.values.length > 500) {
							optionGroup[item.field] = item.values;
							data.basic[index].values = [];
						}
					});
					formMenu.basic = data.basic;
				}

				if (data.cc_prop) {
					itemArr.push(...data.cc_prop);
					formMenu.cc_prop = data.cc_prop;
				} else {
					delete formMenu["cc_prop"];
				}
				if (data.prop) {
					itemArr.push(...data.prop);
					formMenu.prop = data.prop;
				} else {
					delete formMenu["prop"];
				}
				const dataObj = {};
				itemArr.map(item => {
					dataObj[item.field] = "";
				});
				getDocumentList();
				formValue.value = dataObj;
			}
		});
	};

	watch(
		[() => props.treeSelected, () => props.setValue],
		() => {
			setTimeout(() => {
				formItems(props.treeSelected, props.setValue);
			}, 500);
		},
		{ deep: true, immediate: true }
	);

	onMounted(() => { });




	//商品档案列表定制货号、型号、商家搜索
	import { initCustomSearch } from "./customSearch/customSearch.ts";
	// 自定义搜索组件、搜索回调函数和重置回调函数
	const { customSearchComponent, customSearchHandle } = initCustomSearch(currentInstance?.proxy);

	/**
	 * 定义搜索操作的处理方法。
	 *  此函数用点击搜索时候触发相关函数
	 * @returns {void} 无返回值
	 */
	customSearchHandle.search = (params,is_like)=> {
	 
		emit("customSearch", params, searchRef);
		Object.keys(formValue.value).map(item => {
			formValue.value[item] = undefined;
		});
		formRef.value?.resetFields();
		console.log("点击了搜索");
	};


	defineExpose({
		getPlan: id => {
			searchRef.value.getPlanList(id);
		},
		customSearchClear: customSearchHandle.clear//把清除定制搜索表单的方法暴露给父级，高级搜索触发搜索时候清除定制搜索表单内容
	});
</script>

<style scoped lang="scss">
	// :deep(.el-select__selected-item){
	// 	max-width: 77% !important;
	// 	.el-tag.is-closable{
	// 		max-width: 100% !important;
	// 	}
	// }
	.el-form-item {
		:deep(.el-form-item__content > *) {
			width: 100%;
		}
	}
</style>